package com.xinxin.leetcode.problem18;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author ShiXinXin
 * @date 2020-01-21 23:36
 */
public class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        Arrays.sort(nums);
        List<List<Integer>> lists = new ArrayList<>();
        for (int i = 0; i < nums.length - 3; i++) {
            if (nums[i] > target / 4) {
                break;
            }
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }
            int sum = target - nums[i];
            for (int j = i + 1; j < nums.length - 2; j++) {
                if (nums[j] > sum / 3) {
                    break;
                }
                if (j > i + 1 && nums[j] == nums[j - 1]) {
                    continue;
                }
                int l = j + 1, r = nums.length - 1;
                while (l < r) {
                    if (nums[l] > (sum - nums[j]) / 2) {
                        break;
                    }
                    if (nums[i] + nums[j] + nums[l] + nums[r] == target) {
                        lists.add(Arrays.asList(nums[i], nums[j], nums[l], nums[r]));
                        while (l < r && nums[l] == nums[l + 1]) {
                            l++;
                        }
                        while (l < r && nums[r] == nums[r - 1]) {
                            r--;
                        }
                        r--;
                        l++;
                    } else if (nums[i] + nums[j] + nums[l] + nums[r] > target) {
                        r--;
                    } else {
                        l++;
                    }
                }
            }
        }
        return lists;
    }

    public static void main(String[] args) {
        int[] nums = {-1, 0, 1, 2, -1, -4};
        int target = -1;
        System.out.println(new Solution().fourSum(nums, target));
    }
}
